package com.ht.api.callback.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.sql.DataSource;

import com.ht.api.db.Entity;
import com.ht.api.open.OpenUtil;
import com.ht.api.service.CustomerService;
import com.ht.api.service.ExternalContactService;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * 客户群变更事件
 * @author asq
 * @createTime 2025年1月17日 13:26:47
 */
@Slf4j
public class WwxUpdateChatCallbackFunction extends BaseCallbackFunction{
	/** 接口ID：获取客户群详情 */
	private static final long API_ID = 1878802525369536512L;
	
	@Override
	protected List<String> buildSourceDataList(JSONObject params) {
		String updateDetail = params.getStr("UpdateDetail");
		
		List<String> dataList = null;
		switch (updateDetail) {
		case "add_member":
			dataList = buildByAddMember(params);
			break;
			
		case "del_member":
			dataList = buildByDelMember(params);
			break;
			
		case "change_owner":
			
		case "change_name":
			
		case "change_notice":

			dataList = buildByChange(params);
			break;

		default:
			dataList = new ArrayList<>();
			break;
		}
		
		return dataList;
	}
	
	@Override
	protected String getSourceCode(Entity callback, JSONObject params) {
		String updateDetail = params.getStr("UpdateDetail");
		
		String sourceCode = null;
		if ("change_owner".equals(updateDetail) ||
			"change_name".equals(updateDetail) ||
			"change_notice".equals(updateDetail)) {
			sourceCode = "chat_info_change";
		} else {
			sourceCode = "chat_" + updateDetail;
		}
		
		return sourceCode;
	}

	/**
	 * 创建需要写入open_data的data字段值的列表：成员入群
	 * @param params
	 * @return
	 */
	private List<String> buildByAddMember(JSONObject params){
		// 获取
		JSONArray userIds = null;
		int memChangeCnt = params.getInt("MemChangeCnt");
		JSONObject memChangeList = params.getJSONObject("MemChangeList");
		if (memChangeCnt > 1) {
			userIds = memChangeList.getJSONArray("Item");
		} else {
			userIds = JSONUtil.createArray();
			userIds.add(memChangeList.getStr("Item"));
		}
		
        // 解析JSON
		String str = getChatInfo(params);
        JSONObject json = JSONUtil.parseObj(str);
        JSONObject groupChat = json.getJSONObject("group_chat");
        if (groupChat == null) {
            return null;
        }
        
        // 只过滤 member_list
        JSONArray memberList = groupChat.getJSONArray("member_list");
        if (memberList != null && !memberList.isEmpty()) {
            JSONArray filteredMembers = new JSONArray();
            for (int i = 0; i < memberList.size(); i++) {
                JSONObject member = memberList.getJSONObject(i);
                String userId = member.getStr("userid");
                if (userIds.contains(userId)) {
                    filteredMembers.add(member);
                }
            }
            groupChat.set("member_list", filteredMembers);
        }
		
		// 更新接粉组相关的数量
		ExternalContactService.updateInCnt(getTenantDs(appid), groupChat);
		
		return Arrays.asList(json.toString());
	}
	
	/**
	 * 创建需要写入open_data的data字段值的列表：成员退群
	 * @param params
	 * @return
	 */	
	private List<String> buildByDelMember(JSONObject params){
		String createTime = params.getStr("CreateTime");
		DataSource ds = getTenantDs(appid);

		// 获取
		JSONArray userIds = null;
		int memChangeCnt = params.getInt("MemChangeCnt");
		JSONObject memChangeList = params.getJSONObject("MemChangeList");
		if (memChangeCnt > 1) {
			userIds = memChangeList.getJSONArray("Item");
		} else {
			userIds = JSONUtil.createArray();
			userIds.add(memChangeList.getStr("Item"));
		}
		
		JSONArray memChangeArr = JSONUtil.createArray();
		for (int i = 0; i < userIds.size(); i++) {
			JSONObject mem = JSONUtil.createObj();
			String userid = userIds.getStr(i);
			mem.set("userid", userid);
			mem.set("quit_time", createTime);
			mem.set("type", CustomerService.getCustomerType(ds, appid, userid));
			memChangeArr.add(mem);
		}
		
		JSONObject json = JSONUtil.createObj();
		json.set("chat_id", params.getStr("ChatId"));
		json.set("QuitScene", params.getStr("QuitScene"));
		json.set("MemChangeList", memChangeArr);
		return Arrays.asList(json.toString());
	}
	
	/**
	 * 创建需要写入open_data的data字段值的列表：各种变更
	 * @param params
	 * @return
	 */
	private List<String> buildByChange(JSONObject params){
		return Arrays.asList(getChatInfo(params));
	}

	/**
	 * 调用客户群详情接口
	 * @param params
	 * @return
	 */
	private String getChatInfo(JSONObject params) {
		String chatId = params.getStr("ChatId");
        
        // 调用客户群详情接口
        JSONObject wxParam = JSONUtil.createObj();
        wxParam.set("chat_id", chatId);
        wxParam.set("need_name", 1);
		return OpenUtil.call(appid, API_ID, wxParam, true);
	}
}
